package com.shop.cereshop.business.service.tencent.im.impl;

import com.shop.cereshop.business.page.tencent.im.ProductMsgVO;
import com.shop.cereshop.business.param.tencent.im.SendProductMsgParam;
import com.shop.cereshop.business.service.tencent.im.ProductMsgService;
import com.shop.cereshop.commons.constant.CoReturnFormat;
import com.shop.cereshop.commons.domain.business.CerePlatformBusiness;
import com.shop.cereshop.commons.result.Result;
import com.shop.cereshop.commons.tencent.im.enums.im.ActionStatus;
import com.shop.cereshop.commons.tencent.im.enums.im.MsgTypeEnum;
import com.shop.cereshop.commons.tencent.im.model.msg.data.CustomMsgData;
import com.shop.cereshop.commons.tencent.im.model.msg.dto.MsgRequestDTO;
import com.shop.cereshop.commons.tencent.im.model.response.SendGroupMsgResponse;
import com.shop.cereshop.commons.tencent.im.model.response.SendMsgResponse;
import com.shop.cereshop.commons.tencent.im.service.TimMsgService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @description: 商品消息服务实现
 * @author zdd
 * @date 2025/11/5
 * @version 1.0
 */
@Slf4j
@Service
public class ProductMsgServiceImpl implements ProductMsgService {

  @Resource
  private TimMsgService timMsgService;

  @Override
  public Result<Void> sendProductMsg(SendProductMsgParam param, CerePlatformBusiness user) {
    try {
      // 1. 校验参数
      if (StringUtils.isBlank(param.getReceiverId()) && StringUtils.isBlank(param.getGroupId())) {
        return Result.custom(CoReturnFormat.FAIL, "接收者ID和群组ID至少填写一个");
      }

      // 2. 构建商品消息VO
      ProductMsgVO productMsgVO;

      // 3. 判断是否使用前端传入的商品信息
      if (StringUtils.isNotBlank(param.getProductName())
          && StringUtils.isNotBlank(param.getProductImage())
          && param.getPrice() != null) {

        productMsgVO = ProductMsgVO.builder()
            .productId(param.getProductId())
            .productName(param.getProductName())
            .productImage(param.getProductImage())
            .price(param.getPrice())
            .originalPrice(param.getOriginalPrice())
            .senderId(String.valueOf(user.getBusinessUserId()))
            .receiverId(param.getReceiverId())
            .groupId(param.getGroupId())
            .build();

      } else {
        // 兼容路径：前端未传完整信息，返回错误
        log.warn("前端未传入完整的商品信息，商品ID: {}", param.getProductId());
        return Result.custom(CoReturnFormat.FAIL, "请传入完整的商品信息（名称、图片、价格）");
      }

      // 4. 构建消息数据
      MsgRequestDTO requestDTO = productMsgVO.covertToMsgRequestDTO();
      CustomMsgData msgData = productMsgVO.covertToCustomMsgData();

      // 5. 发送消息
      boolean isSendSuccess = false;
      if (StringUtils.isNotBlank(param.getGroupId())) {
        // 发送群聊消息
        SendGroupMsgResponse response = timMsgService.sendGroupMsg(MsgTypeEnum.CUSTOM, msgData, requestDTO);
        if (ActionStatus.OK.getStatus().equals(response.getActionStatus())) {
          isSendSuccess = true;
          log.info("群聊商品消息发送成功，群组ID: {}, 商品ID: {}", param.getGroupId(), param.getProductId());
        }
      } else {
        // 发送单聊消息
        SendMsgResponse response = timMsgService.sendC2cMsg(MsgTypeEnum.CUSTOM, msgData, requestDTO);
        if (ActionStatus.OK.getStatus().equals(response.getActionStatus())) {
          isSendSuccess = true;
          log.info("单聊商品消息发送成功，接收者ID: {}, 商品ID: {}", param.getReceiverId(), param.getProductId());
        }
      }

      if (isSendSuccess) {
        return Result.success();
      } else {
        return Result.custom(CoReturnFormat.FAIL, "商品消息发送失败");
      }

    } catch (Exception e) {
      log.error("发送商品消息异常", e);
      return Result.custom(CoReturnFormat.FAIL, "发送商品消息失败：" + e.getMessage());
    }
  }

}
